package com.ny.controller;
import com.ny.entity.Classrooms;
import com.ny.entity.Reservations;
import com.ny.entity.Users;

import com.ny.service.ClassroomService;
import com.ny.service.ReservationService;
import com.ny.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
//    UserService userService = new UserServiceImpl();
    @Autowired
    private UserService userService;
    @Autowired
    private ClassroomService classroomService;
    @Autowired
    private ReservationService reservationService;
    @RequestMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password,Model model,HttpSession session) {
        Users user = userService.login(username, password);
        session.setAttribute("user", user);
        if (user!= null) {
            System.out.println(user);
            List<Classrooms> classroomsList = classroomService.findAllClassrooms();
            System.out.println(classroomsList);
            model.addAttribute("classroomList", classroomsList);
//            model.addAttribute("user", user);
            return "classroom";
        } else {
            model.addAttribute("error", "用户名或密码错误");
            return "login";
        }
    }


    @GetMapping("/searchClassrooms")
    public String searchClassrooms(
            @RequestParam(required = false) String classroomName,
            @RequestParam(required = false) String capacity,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String location,
            @RequestParam(required = false) String description,
            Model model) {
        List<Classrooms> classroomList = classroomService.searchClassrooms(classroomName, capacity, status, location, description);
        System.out.println("获取到的数据"+classroomList);
        model.addAttribute("classroomList", classroomList);
        return "classroom";
    }
//    退出登录
@GetMapping("/logout")
public String logout(HttpServletRequest request) {
    HttpSession session = request.getSession(false);
    if (session!= null) {
        session.invalidate();
    }
    return "login";
}

    @GetMapping("/my-reservations")
    public String myReservations(@RequestParam("userId") int userId, Model model) {
        List<Reservations> reservations = reservationService.findReservationsByUserId(userId);
        System.out.println(reservations);
        model.addAttribute("reservations", reservations);
        return "reservation-list";
    }

}
